package com.bdqn.ch06.controller;

import com.bdqn.ch06.entity.User;
import com.bdqn.ch06.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;


    //配置欢迎页面
    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        return "login";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }


    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "usrName") String usrName,
                          @RequestParam(value = "usrPassword") String usrPassword,
                          Model model,
                          HttpSession session) {
        User user = userService.findByUserNameBiz(usrName);
        if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!user.getUsrPassword().equals(usrPassword)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                session.setAttribute("sessionuser", user);
                return "main";
            }
        }
    }


    @ResponseBody
    @RequestMapping("/getuserid/{id}")
    public Object getUser(@PathVariable("id") Long usrId) {
        User user = userService.getUserByIdService(usrId);
        System.out.println(user.toString());
        return user;
    }

    @RequestMapping("/logout")
    public String logout() {
        System.out.println("logout");
        return "";
    }

}
